<!--
*@Author: QWP
*@Description: 自定义导出
*@Date: 2024-07-08 17:04:38
-->
<template>
  <u-dialog
    title="自定导出模版"
    :hideBtns="['submit']"
    :destroyOnClose="false"
    placement="right"
    v-bind="$attrs"
    @close="dialogClose">
    <a-layout class="f-h-100">
      <u-table-header>
        <a-form :model="modoulForm">
          <a-form-item label="导出模版">
            <a-select v-model:value="modoulForm.templateId" 
              :options="moudleOptions"
              :fieldNames="{ label: 'temName', value: 'keyid' }"
              @change="modelSelect">
              <template #option="{ keyid, temName, icon }">
                <a-row>
                  {{ temName }} 
                  <a-col flex="1" v-if="keyid != '1'">
                    <div class="f-fr s-text-color1" @click="(e) => deletModule(keyid, e)">删除</div>
                  </a-col>
                </a-row>
              </template>
            </a-select>
          </a-form-item>
        </a-form>
      </u-table-header>

      <u-table-content class="f-margin-b16"
        style="overflow: auto">
        <a-row>导出字段</a-row>
        <u-busi-card v-for="item in collapses"
          :title="item.label"
          class="f-margin-b16">
          <template #extra>
            <a-checkbox v-model:checked="checkAllData[item.activeKey]" 
              :indeterminate="(checkData[item.activeKey] || []).length != 0 && !checkAllData[item.activeKey]"
              @change="onCheckAllChange(item.activeKey, checkAllData[item.activeKey], (item['els'] || []))">全选
            </a-checkbox>
          </template>
          <a-checkbox-group v-model:value="checkData[item.activeKey]"
            style="width: 100%">
            <a-row :gutter="[12, 12]">
              <a-col :span="4" v-for="cItem in (item['els'] || [])"
                :key="cItem['dataIndex']">
                <a-checkbox :value="cItem['dataIndex']"
                  :name="cItem['title']"
                  @change="(e) => {
                    e.target.item = cItem
                    busiItemChange(item.activeKey, e)
                  }">
                  {{ cItem['title'] }}
                </a-checkbox>
              </a-col>
            </a-row>
            </a-checkbox-group>
        </u-busi-card>
        <div class="f-w-100" style="height: 16px"></div>
      </u-table-content>
    </a-layout>
    <template #footerBefore>
      <u-icon-button itype="save" @click="saveModel">保存为模版</u-icon-button>
      <u-icon-button itype="export" @click="exportBtn">导出</u-icon-button>
    </template>
  </u-dialog>
</template>

<script lang='ts' setup>
import { ref, reactive, computed, onMounted, h, useAttrs, watch } from 'vue' 
import { useLoginStore,  useBaseStore } from '@/store'
import { storeToRefs } from 'pinia'
import { useRoute, useRouter } from 'vue-router'
import { _IFormEl, _IExtra } from '@/components/common/form/interface';
import { Button, Col, FormInstance, FormItemProps, Input, Modal, Row, Space } from 'ant-design-vue';
import { HomeOutlined, FileTextOutlined, UploadOutlined } from '@ant-design/icons-vue';
import { TreeProps } from 'ant-design-vue/es/vc-tree';
import { ColumnProps } from 'ant-design-vue/es/table';
import { _IColumnProps } from '@/components/common/tableEdit/interface.ts'
import { fileCols } from '@/common/model/fileCols'
import { cloneDeep } from 'lodash'
import { numberToText } from '@/common/model/base'
import { alertC, messageC, numberC, isValue, confirmC, nullC } from '@/util/common'
import { initSelEls} from './data/colData.ts'
import * as exportModelApi from '@/service/personalSet/exportmodel'
import { UIconFont } from '@/components/common/iconfont';
import { personInfoApi } from '@/service/personalSet' 

interface Props {
  params?: object,
  keyid?: string,
  searchF: any | object
}
const props = withDefaults(defineProps<Props>(), {
  params: {},
  searchF: {}
})
const route = useRoute()
const attrs = useAttrs()
const { userInfo } = storeToRefs(useLoginStore())

const emits = defineEmits(['success', 'close'])

// 表单相关信息
const formRef = ref<FormInstance>()
const checkData = ref({})
const checkAllData = ref({})
const formLoading = ref<boolean>(false)
const results = ref<objetc>({})

const bodyStyle = {
  background: 'rgb(245, 246, 247)'
}

const modoulForm = ref<object>({})
const moudleOptions = ref<any[]>([])

const tSelEls = initSelEls()

// 初始化需要勾选的字段
let collapses = computed(() => tSelEls)

// 获取模版数据
const getSearch = async () => {
  try {
    const res = await exportModelApi.page({
      model: {}, size: 10000, current: 1
    })
    if(res.code == 0) {
      moudleOptions.value = res.data.records || []
    }
  } catch (error) {}
}

// 按模版导出
const exportBtn = async (value, option) => {
  debugger
  if(!modoulForm.value['templateId']) {
    messageC("请先选择导出模版!");
    return
  }
  let info = moudleOptions.value.find(i => i.keyid == modoulForm.value['templateId']) || {}
  try {
    formLoading.value = true;
    let tSesarchF = cloneDeep(props.searchF)
    tSesarchF.model.templateId = modoulForm.value['templateId']
    const res = await personInfoApi.download({ ...tSesarchF, size: 100000,  filename: `人事信息-${nullC(info['temName'])}` })
  } catch (error) { }
  formLoading.value = false;
}

// 保存模版
let isSaveing = ref<boolean>(false);
const saveModel = async () => {
  if(Object.keys(results.value).length == 0) {
    messageC("请先选中模版字段！");
    return
  }

  const modal = Modal.confirm();

  let modelLoading = ref<boolean>(false)
  const save = async (temName) => {
    if(!temName) {
      messageC("请先输入模版名称！");
      return
    }

    if(isSaveing.value)  return
    modelLoading.value = true;
    try {
      isSaveing.value = true;
      const res = await exportModelApi.add({
        maps: results.value,
        temName
      })
      if(res.code == 0) {
        messageC(res.msg, 'success')
        getSearch()
        modal.destroy()
      }
      else {
        messageC(res.msg, 'error')
      }
    } catch (error) {}
    isSaveing.value = false;
    modelLoading.value = false;
  }

  let modelValue = ''
  modal.update({ title: '模版名称', icon: h(''),
    width: '400px',
    content: h(Row, [
      h(Col, { flex: 1}, [ h(Input,  { onChange: (e) => modelValue = e.target.value, style: { width: '350px' } }) ])
    ]),
    footer: h(Row, { justify: 'end', style: { padding: '16px 0 10px' }, }, [
      h(Space, [
        h(Button, { type: 'primary', loading: modelLoading.value, onClick: () => {
          save(modelValue)
        } }, '保存'),
        h(Button, { danger: true, ghost: true, onClick: () => modal.destroy() }, '关闭')
      ])
    ])
  }) 
}

// 模版选择
const modelSelect = (value, option:Option | Array<Option>) =>  {
  const { fields } = option;
  results.value = {};
  let fieldNames = fields.map(i => {
    results.value[i.fieldName] = i.fieldNick
    return i.fieldName
  });
  
  checkData.value = {}
  checkAllData.value = {}
  collapses.value.forEach(item => {
    let { els, activeKey } = item;
    let currents = els.filter(i => fieldNames.includes(i.dataIndex)).map(i => i.dataIndex);
    let currents1 = els.filter(i => fieldNames.includes(Object.keys(i.exportKey || {})[0])).map(i => i.dataIndex)
    checkData.value[activeKey] = Array.from(new Set([...currents, ...currents1]));
    if(checkData.value[activeKey].length == els.length) {
      checkAllData.value[activeKey] = true
    }
  })
}

// 全选和取消全选
const onCheckAllChange = (key: string, checked: boolean, els: any[]) => {
  checkData.value[key] = checked ? els.map(i => i['key'] || i['dataIndex']) : []
  els.forEach(item => {
    busiItemChange(key, { 
      target: {
        checked,
        value: item['key'] || item['dataIndex'],
        item
      }
    })
  })
}

// 每一项选择框的点击
const busiItemChange = (activeKey, target) => {
  const { checked, value, item } = target.target
  
  if(checked == true) {
    if(item.exportKey) {
      results.value = { ...results.value, ...(item.exportKey || {}) }
    } else {
      results.value[value] = item['title'];
    }
  }  
  else {
    if(item.exportKey) { 
      for(let key in (item.exportKey || {})) {
        delete results.value[key]
      }
    }
    else {
      delete results.value[value]
    }
  }
}

// 删除模版
const deletModule = async(val, e) => {
  e.stopPropagation();
  try {
    await alertC("确认删除？", 'confirm');

    const res = await exportModelApi.del({ ids: val })
    if(res.code == 0) {
      messageC(res.msg, 'success');
      getSearch()
    }
    else {
      messageC(res.msg, 'error');
    }

  } catch (error) {}
}

// 弹窗关闭
const dialogClose = () => {
  checkAllData.value = {}
  checkData.value = {}
  results.value = {}
}

watch(() => attrs.open, async (nval, oval) => {
  if (nval == true) {
    getSearch()
  }
})
</script>

<style lang='scss' >
.u-personal-manager-edit {
  .ant-collapse-item-disabled {
    .ant-collapse-header {
      cursor: default;
      .ant-collapse-header-text {
        color: rgba(0, 0, 0, 0.88)
      }
    }
  }
}
.u-side-tree-custom {
  .ant-tree-switcher {
    display: none
  }
  .ant-tree-node-content-wrapper {
    position: relative;
    line-height: 32px ;
    &:hover {
      color: #1890ff;
      background-color: rgba(24, 144, 255, 0.2);
    }
    .ant-tree-iconEle {
      line-height: 32px ;
    }
    .ant-tree-title {
      font-size: 14px;
      padding-left: 6px
    }
    .u-tree-clear-icon {
      position: absolute;
      right: 20px;
      top: 50%;
      transform: translateY(-50%);
      font-size: 12px;
      color: #AAAAAA 
    }
  }
}
</style>